package context

import (
	"errors"
	"fmt"
	"strconv"
)

//context 解析参数

type Parser struct {
	Params map[string]interface{}
	Data   interface{}
}

func (c *Parser) LoadParams(data interface{}, moduleId int) bool {
	c.Params = make(map[string]interface{})
	c.Data = data
	moduleParams := GetModuleFuncParams(moduleId)
	if moduleParams == nil {
		return true
	}
	if data == nil {
		return false
	}
	if mapData, ok := data.(map[string]interface{}); ok {
		for _, k := range moduleParams {
			field, exist := mapData[k]
			if !exist {
				panic(fmt.Sprintf("invalid param. moduleId: [%v] need param: [%v]", moduleId, k))
				return false
			}
			c.Params[k] = interface{}(field)
		}
		return true
	}
	//todo struct 支持
	return true
}

func (c *Parser) GetParam(k string) (interface{}, error) {
	if v, ok := c.Params[k]; ok {
		return v, nil
	}
	return nil, errors.New(fmt.Sprintf("not exist param %v", k))
}

func (c *Parser) GetIntParam(k string) (int, error) {
	if v, ok := c.Params[k]; ok {
		p := fmt.Sprintf("%v", v)
		return strconv.Atoi(p)
	}
	return 0, errors.New(fmt.Sprintf("not exist param %v", k))
}

func (c *Parser) GetStringParam(k string) (string, error) {
	if v, ok := c.Params[k]; ok {
		p := fmt.Sprintf("%v", v)
		return p, nil
	}
	return "", errors.New(fmt.Sprintf("not exist param %v", k))
}
